import React, { Component } from "react";

export default class TodoItem extends Component {
  constructor(props) {
    super();
    this.state = {
      completedText: props.completed ? "已完成❤️" : "未完成💔",
    };
  }

  // 旧版的写法
  // componentWillReceiveProps(nextProps) {
  //   this.setState({
  //     completedText: nextProps.completed ? "已完成❤️" : "未完成💔",
  //   });
  // }

  // 新版的写法 16.3以上建议使用
  static getDerivedStateFromProps(nextProps) {
    return {
      completedText: nextProps.completed ? "已完成❤️" : "未完成💔",
    };
  }

  shouldComponentUpdate(nextProps) {
    // return true;
    return nextProps.completed !== this.props.completed;
    // if (nextProps.completed !== this.props.completed) {
    //   return true;
    // } else {
    //   return false;
    // }
  }

  render() {
    console.log(this.props);
    const { id, completed, title } = this.props;
    return (
      <div>
        <input
          type="checkbox"
          checked={completed}
          onChange={() => this.props.change(id, completed)}
        />{" "}
        ---
        <span>{title}</span>---
        <span>{this.state.completedText}</span>---
        <input
          type="button"
          value="删除"
          onClick={() => this.props.click(id)}
        />
      </div>
    );
  }
}
